#!/bin/sh
#
# Simple Redis init.d script conceived to work on Linux systems
# as it does use of the /proc filesystem.
#
# description: Redis is an in memory key-value store database
#
### BEGIN INIT INFO
# Provides: redis<%= @port %>
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Required-Start: <%= @required_start %>
# Required-Stop: <%= @required_stop %>
# Description: redis<%= @port %> init script
### END INIT INFO

REDISNAME=<%= @name %>
REDISPORT=<%= @port %>
<% case @platform %>
<% when 'ubuntu','debian','fedora' %>
EXEC="su -s /bin/sh -c '<%= File.join(@bin_path, 'redis-server') %> <%= @configdir %>/${REDISNAME}.conf' <%= @user %>"
<% else %>
EXEC="runuser <%= @user %> -c \"<%= File.join(@bin_path, 'redis-server') %> <%= @configdir %>/${REDISNAME}.conf\""
<% end %>
CLIEXEC=<%= File.join(@bin_path, 'redis-cli') %>

<% connection_string = String.new %>
<% if @unixsocket.nil? %>
  <% connection_string << " -p #{@port}" %>
  <% connection_string << " -h #{@address.respond_to?(:first) ? @address.first : @address }" if @address %>
<% else %>
  <% connection_string << " -s #{@unixsocket}" %>
<% end %>
<% connection_string  << " -a '#{@requirepass}'" unless @requirepass.nil? %>

PIDFILE=<%= @piddir %>/redis_${REDISNAME}.pid

if [ ! -d <%= @piddir %> ]; then
    mkdir -p <%= @piddir %>
    chown <%= @user %>  <%= @piddir %>
fi

ulimit -n <%= @ulimit %>

case "$1" in
    status)
        if [ -f $PIDFILE ]
        then
          echo "redis$REDISNAME $PIDFILE exists, pid is $(cat $PIDFILE), should be running"
          ps -p $(cat $PIDFILE) >/dev/null 2>&1
          exit $?
        else
          echo "redis$REDISNAME $PIDFILE doesn't exist"
          exit 3
        fi
        ;;
    start)
        if [ -f $PIDFILE ]
        then
                echo "$PIDFILE exists, process is already running or crashed"
        else
                echo "Starting Redis server..."
                eval $EXEC
        fi
        ;;
    stop)
        if [ ! -f $PIDFILE ]
        then
                echo "$PIDFILE does not exist, process is not running"
        else
                PID=$(cat $PIDFILE)
                echo "Stopping ..."

                <%= "$CLIEXEC #{connection_string} save" if @shutdown_save %>
                $CLIEXEC <%= connection_string %> shutdown

                while [ -x /proc/${PID} ]
                do
                    echo "Waiting for Redis to shutdown ..."
                    sleep 1
                done
                echo "Redis stopped"
        fi
        ;;
    *)
        echo "Please use start or stop as first argument"
        ;;
esac
